package Fan.Mongodb;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

import com.google.gson.Gson;

public class HandleMongo {
	//显示所有的数据库信息
	public void showDatabase()throws Exception{
		Gson gson = new Gson();
		FileInputStream file = new FileInputStream("database.xml");
		SAXBuilder saxBuilder = new SAXBuilder();
		Document document = saxBuilder.build(file);
		Element root = document.getRootElement();
		List<Element> list = root.getChildren();
		if(list.size()>0){
			for(Element x : list){
				String name = x.getAttributeValue("name");
				String paths = x.getAttributeValue("databasePath");
				System.out.println("数据库："+name+"，路径："+paths);
			}
		}
		System.out.println("数据库数量："+list.size());
		
	}
	//插入数据库信息
	public void insertNewDatabase(String databasePath, String name)throws Exception{
		Gson gson = new Gson();
		FileInputStream file = new FileInputStream("database.xml");
		SAXBuilder saxBuilder = new SAXBuilder();
		Document document = saxBuilder.build(file);
		Element root = document.getRootElement();
		
		Element dataBaseElement = new Element("database");
		dataBaseElement.setAttribute("name", name);
		dataBaseElement.setAttribute("databasePath", databasePath);
		root.addContent(dataBaseElement);
		
		XMLOutputter out = new XMLOutputter();
		out.output(document, new FileOutputStream("database.xml"));
	}
	//创建数据库
	public void createDataBase(String path,String name) throws Exception{
		this.insertNewDatabase(path, name);
		//文件内容
		Element root = new Element("database");
		
		//吧文件内容放入集合
		Document document = new Document();
		document.setRootElement(root);
		
		//根据集合信息和生成文件路径生成xml文件
		FileOutputStream file = new FileOutputStream(path);
		XMLOutputter out = new XMLOutputter();
		out.output(document, file);
	}
	//建表
	public void createTable(String databaseName, String tableName)throws Exception{
		//根据数据库名称获取是否存在该数据库，如果存在则返回路径，否则返回notFound
		String url = this.isDatabase(databaseName);
		if(url.equals("notFound")){
			System.out.println("未发现对应数据库！");
		}else{
			//插入数据库-创建表
			FileInputStream databaseFile = new FileInputStream(url);
			SAXBuilder databaseSAXBuilder = new SAXBuilder();
			
			Document databaseDocument = databaseSAXBuilder.build(databaseFile);
			Element databaseRoot = databaseDocument.getRootElement();
			Element tableEle = new Element("table");
			tableEle.setAttribute("name",tableName);
			databaseRoot.addContent(tableEle);
			
			XMLOutputter out = new XMLOutputter();
			out.output(databaseDocument, new FileOutputStream(url));
		}
	}
	//表内插入数据
	public void insertTableData(String databaseName, String tableName, Object o) throws Exception{
		Gson gson = new Gson();
		String json = gson.toJson(o);
		Map map = gson.fromJson(json, Map.class);
		Map base = new HashMap();
		base.putAll(map);
		
		//获取数据库路径
		String databasePath = this.isDatabase(databaseName);
		if(databasePath.equals("notFound")){
			System.out.println("未获取到数据库："+databaseName);
			return;
		}
		//验证表是否在该数据库当中
		String rs = this.isTable(databasePath, tableName);
		if(rs.equals("found")){
			FileInputStream file = new FileInputStream(databasePath);
			SAXBuilder saxBuilder = new SAXBuilder();
			Document document = saxBuilder.build(file);
			Element root = document.getRootElement();
			List<Element> list = root.getChildren();
			for(Element ele : list){
				if(ele.getAttributeValue("name").equals(tableName)){
					Element data = new Element("data");
					data.addContent(gson.toJson(base));
					ele.addContent(data);
				}
			}
			
			XMLOutputter out = new XMLOutputter();
			out.output(document, new FileOutputStream(databasePath));
		}
	}
	public void updateTableData(String databaseName, String tableName, Object o) throws Exception{
		//获取数据库路径
		String databasePath = this.isDatabase(databaseName);
		if(databasePath.equals("notFound")){
			System.out.println("未获取到数据库："+databaseName);
			return;
		}
		//验证表是否在该数据库当中
		String rs = this.isTable(databasePath, tableName);
		if(rs.equals("found")){
			FileInputStream file = new FileInputStream(databasePath);
			SAXBuilder saxBuilder = new SAXBuilder();
			Document document = saxBuilder.build(file);
			Element root = document.getRootElement();
			for(Element ele : (List<Element>)root.getChildren()){
				if(ele.getAttributeValue("name").equals(tableName)){
					//ele.addContent(gson.toJson(map));
					for(Element dataEle : (List<Element>)ele.getChildren()){
						Gson gson = new Gson();
						Map map = gson.fromJson(dataEle.getText(), Map.class);
						Map newMap = gson.fromJson(gson.toJson(o), Map.class);
						if(map.get("id").equals(newMap.get("id"))){
							map.putAll(newMap);
							Element data = new Element("data");
							data.setText(gson.toJson(map));
							ele.removeContent(dataEle);
							ele.addContent(data);
							break;
						}
					}
				}
			}
			
			XMLOutputter out = new XMLOutputter();
			out.output(document, new FileOutputStream(databasePath));
		}
	}
	public void deleteTableData(String databaseName, String tableName, Object o) throws Exception{
		//获取数据库路径
		String databasePath = this.isDatabase(databaseName);
		if(databasePath.equals("notFound")){
			System.out.println("未获取到数据库："+databaseName);
			return;
		}
		//验证表是否在该数据库当中
		String rs = this.isTable(databasePath, tableName);
		if(rs.equals("found")){
			FileInputStream file = new FileInputStream(databasePath);
			SAXBuilder saxBuilder = new SAXBuilder();
			Document document = saxBuilder.build(file);
			Element root = document.getRootElement();
			for(Element ele : (List<Element>)root.getChildren()){
				if(ele.getAttributeValue("name").equals(tableName)){
					//ele.addContent(gson.toJson(map));
					for(Element dataEle : (List<Element>)ele.getChildren()){
						Gson gson = new Gson();
						Map map = gson.fromJson(dataEle.getText(), Map.class);
						Map newMap = gson.fromJson(gson.toJson(o), Map.class);
						if(map.get("id").equals(newMap.get("id"))){
							ele.removeContent(dataEle);
							break;
						}
					}
				}
			}
			
			XMLOutputter out = new XMLOutputter();
			out.output(document, new FileOutputStream(databasePath));
		}
	}
	public void selectTableDate(String databaseName, String tableName) throws Exception{
		//获取数据库路径
				String databasePath = this.isDatabase(databaseName);
				if(databasePath.equals("notFound")){
					System.out.println("未获取到数据库："+databaseName);
					return;
				}
				//验证表是否在该数据库当中
				String rs = this.isTable(databasePath, tableName);
				if(rs.equals("found")){
					FileInputStream file = new FileInputStream(databasePath);
					SAXBuilder saxBuilder = new SAXBuilder();
					Document document = saxBuilder.build(file);
					Element root = document.getRootElement();
					for(Element ele : (List<Element>)root.getChildren()){
						System.out.println("数据库【"+databaseName+"】，路径【"+databasePath+"】，表【"+tableName+"】");
						if(ele.getAttributeValue("name").equals(tableName)){
							//ele.addContent(gson.toJson(map));
							for(Element dataEle : (List<Element>)ele.getChildren()){
								Gson gson = new Gson();
								Map map = gson.fromJson(dataEle.getText(), Map.class);
								System.out.println("数据：编号【"+map.get("id")+"】,姓名【"+map.get("name")+"】，年龄【"+map.get("age")+"】，备注【"+map.get("remark")+"】");
							}
						}
					}
				}
	}
	//判断是否是数据库，如果是则返回数据库的路径，否则返回notFound
	public String isDatabase(String databaseName) throws Exception{
		FileInputStream file = new FileInputStream("database.xml");
		SAXBuilder saxBuilder = new SAXBuilder();
		Document document = saxBuilder.build(file);
		Element root = document.getRootElement();
		List<Element> list = root.getChildren();
		
		String url = "notFound";
		if(list.size()>0){
			for(Element x : list){
				String name = x.getAttributeValue("name");
				if(name.equals(databaseName)){
					url = x.getAttributeValue("databasePath");
				}
			}
		}
		return url;
	}
	//判断是否存在该表，如果不存在则返回notFound，否则返回found
	public String isTable(String databasePath, String tableName) throws Exception{
		FileInputStream file = new FileInputStream(databasePath);
		SAXBuilder saxBuilder = new SAXBuilder();
		Document document = saxBuilder.build(file);
		Element root = document.getRootElement();
		List<Element> list = root.getChildren();
		for(Element ele : list){
			if(ele.getAttributeValue("name").equals(tableName)){
				return "found";
			}
		}
		System.out.println("未发现表："+tableName);
		return "notFoundTable";
	}
}
